from sqlite3 import dbapi2 as sqlite
import os

class DataController(object):
    __default = object
    def __init__(self, dbname):
        self.dbname = dbname
        create = False
        if not os.path.exists(dbname):
            create = True
        self.con = sqlite.connect(dbname)
	if create: self.create_tables()
    #def __del__(self):
    #    self.con.close()
    def commit(self):
        self.con.commit()
    def create_tables(self):
        self.con.execute('create table if not exists source(path)')
        self.con.execute('create table if not exists settings(key,value)')
        self.con.execute('create index if not exists settings_key on settings(key)')
        self.commit()
    def get(self, key, default=__default):
        res = self.con.execute("select value from settings where key='%s'"%key).fetchone()
        if res:
            return res[0]
        if default == self.__default:
            raise KeyError(key)
        return default
    def set(self, key, value):
        if self.get(key, default=False):
            self.con.execute("update settings set value='%s' where key='%s'"%(value,key))
        else:
            self.con.execute("insert into settings(key,value) values ('%s','%s')"%(key,value))
        self.commit()
    def get_sources(self):
        rows = self.con.execute('select path from source')
        return [row[0] for row in rows]
    def add_source(self, path):
        self.con.execute("insert into source(path) values('%s')"%path)
        self.commit()
    def remove_source(self, path):
        self.con.execute("delete from source where path='%s'"%path)
        self.commit()
    def move_database(self, destination):
        abs_dest = os.path.abspath(destination)
        abs_dir = os.path.dirname(abs_dest)
        if not os.path.exists(abs_dir):
            raise Exception('Destination %s does not exist.'%abs_dir)
        self.con.close()
        source = open(self.dbname)
        dest = open(abs_dest, 'wb')
        data = source.read()
        dest.write(data)
        source.close()
        dest.close()
        os.remove(self.dbname)
        self.dbname = abs_dest
        self.con = sqlite.connect(abs_dest)

if __name__ == '__main__':
    dc = DataController('test.db')

5 +2
